# pattern_tab.pl
# function for tabform

# load modules
require "./electric_bulletin_board-lib.pl";
require "./config.pl";


# pattern_tab()
# pattern tab generate functions
sub pattern_tab() {
	# configure form start
	print &ui_form_start("index.cgi", "get");
	
	# tab name
	print &ui_hidden("tab", "pattern");
	
	# select pattern
	my %filelist = ();
	&read_file("$module_root_directory/pattern/file.list", \%filelist);
	my @filelist_key = keys(%filelist);
	
	foreach my $key (@filelist_key) {
		my $date = $key;
		$date =~ s/\..*$//;
		
		$filelist{$key} = &serial2time($date) . " $filelist{$key}";
	}
	
	my @filelist_value = values(%filelist);
	@filelist_value = sort(@filelist_value);
	@filelist_value = reverse(@filelist_value);
	
	print &item_br();
	print &ui_multi_select("selectpattern", undef, \@filelist_value, 10, undef, undef, ("パターンリスト", "表示パターン"), 300);
	
	# select limmit value
	my @limmit_value = ();
	for (my $i=1; $i<=255; $i++) {
		push(@limmit_value, $i);
	}
	print "<h4>二階調化しきい値</h4>";
	print &ui_select("limmit_value", "128", \@limmit_value);
	
	# run button
	print &item_hr();
	print &ui_submit($text{'pattern_submit'});
	
	# configure form end
	print &ui_form_end();
}

# pattern_run()
# pattern run functions
sub pattern_run() {
	# check exist select pattern
	if ($in{'selectpattern'} eq "") {
		return;
	} else {
		print "select pattern = exist!", "<br>";
	}
	
	# search file name from file.list
	my @selectpattern = split(/\r\n/, $in{'selectpattern'});
	my $match_filename_array_ref;
	$match_filename_array_ref = &search_from_file("$module_root_directory/pattern/file.list", \@selectpattern);
	
	# create pattern
	my %pattern_group = ();
	foreach my $filename (@$match_filename_array_ref) {
		
		# image binary to numeric value
		my @pattern_line_array = ();
		my $cnt = 2;
		my $image_array_ref = &image2string("$module_root_directory/pattern/$filename");
		
		# limmit image size (depend on LCD pannel)
		if ($$image_array_ref[0] > 128 && $$image_array_ref[1] > 64) {
			print "error: image size is to large!";
			next;
		}
		
		# search over limmit value and add dot location to @sendarray
		for (my $y=0; $y<$$image_array_ref[1]; $y++) {
			for (my $x=0; $x<$$image_array_ref[0]; $x++) {
				if ($$image_array_ref[$cnt++] <= $in{'limmit_value'}) {                    # require check
					push(@pattern_line_array, sprintf("%.3d", $x) . sprintf("%.3d", $y));
				}
			}
		}
		
		$" = ",";
		$pattern_group{$filename} = "@pattern_line_array";
	}
	
	# delete group.list
	&unlink_file("$module_root_directory/pattern/group.list");
	
	# save pattern to group.list
	&write_file("$module_root_directory/pattern/group.list", \%pattern_group);
	
	# show LCD pannel
	system("touch $lockfile");
	system("./send.pl /dev/ttyUSB0 $module_root_directory/pattern/group.list $lockfile &");
	
	return;
}

